import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:gradient_app_bar/gradient_app_bar.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/providers/image_list_model.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:provider/provider.dart';

ShareProvider _shareProvider; // 全局共享数据
ImageListModel _imageListModel;
BuildContext _context;
class HeroAnimationRouteB extends StatelessWidget {
  final File file;

  HeroAnimationRouteB({this.file});
  @override
  Widget build(BuildContext context) {
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    _imageListModel = Provider.of<ImageListModel>(context, listen: true);
    _context = context;
    return Scaffold(
      appBar: _myAppBar(),
      body: _body(),
    );
  }

  Widget _body() {
    return Center(
      child: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(Su().w(30)),
        child: Image.file(
          file,
          fit: BoxFit.fitWidth,
          width: 300,
        ),
      ),
    );
  }

  // 自定义appbar
  PreferredSizeWidget _myAppBar() {
    return GradientAppBar(
      title: Text('查看图片'),
      centerTitle: true,
      gradient: LinearGradient(
        colors: _shareProvider.themeColor,
      ),
      actions: <Widget>[
        _actionWidget(),
      ],
    );
  }

  // 右上角action
  Widget _actionWidget() {
    return Container(
      width: Su().w(180),
      child: Row(
        children: <Widget>[
          _editAction(),
          _deleteAction(),
        ],
      ),
    );
  }

  // 删除图标
  Widget _deleteAction() {
    return IconButton(
      padding: EdgeInsets.all(0),
      icon: Icon(
        Icons.delete,
      ),
      color: Colors.white,
      tooltip: '删除',
      onPressed: () {
        _imageListModel.deleteItem(file: file);
        Navigator.pop(_context);
      },
    );
  }

  // 编辑图标
  Widget _editAction() {
    return IconButton(
      padding: EdgeInsets.all(0),
      icon: Icon(
        Icons.edit,
      ),
      color: Colors.white,
      tooltip: '编辑',
      onPressed: () async {
        File newFile = await _imageCropper(file);
        _imageListModel.updateItem(oldFile: file, newFile: newFile);
        Navigator.pop(_context);
      },
    );
  }

    // 编辑图片插件
  Future<File> _imageCropper(File imageFile) async {
    File croppedFile = await ImageCropper.cropImage(
      sourcePath: imageFile.path,
    );
    // 自定义图片名称
    String imageName = DateTime.now().millisecondsSinceEpoch.toString() + '.jpg'; 
    String pathName = await Su().getFileName(imageName);
    File newFile = await croppedFile.copy(pathName);
    return newFile;
  }
}
